import axios from 'axios'

// 创建API实例
const api = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL || 'http://localhost:8000/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    // 添加认证token等
    const token = localStorage.getItem('auth_token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    console.error('API Error:', error)
    return Promise.reject(error)
  }
)

// 机器狗控制API
export const robotControlApi = {
  // 获取机器狗状态
  getStatus: () => api.get('/robot/status'),
  
  // 移动控制
  move: (direction, speed = 50) => api.post('/robot/move', { direction, speed }),
  
  // 停止移动
  stop: () => api.post('/robot/stop'),
  
  // 紧急停止
  emergencyStop: () => api.post('/robot/emergency-stop'),
  
  // 设置姿态
  setPosture: (posture) => api.post('/robot/posture', { posture }),
  
  // 设置速度
  setSpeed: (speed) => api.post('/robot/speed', { speed }),
  
  // 移动到指定位置
  moveTo: (x, y, z = 0) => api.post('/robot/move-to', { x, y, z }),
  
  // 获取位置信息
  getPosition: () => api.get('/robot/position'),
  
  // 获取电池信息
  getBattery: () => api.get('/robot/battery')
}

// 摄像头控制API
export const cameraApi = {
  // 获取摄像头列表
  getCameras: () => api.get('/cameras'),
  
  // 获取实时视频流URL
  getStreamUrl: (cameraId) => api.get(`/cameras/${cameraId}/stream`),
  
  // 截图
  takeScreenshot: (cameraId) => api.post(`/cameras/${cameraId}/screenshot`),
  
  // 开始录制
  startRecording: (cameraId) => api.post(`/cameras/${cameraId}/record/start`),
  
  // 停止录制
  stopRecording: (cameraId) => api.post(`/cameras/${cameraId}/record/stop`),
  
  // PTZ控制
  ptzControl: (cameraId, action, value) => api.post(`/cameras/${cameraId}/ptz`, { action, value }),
  
  // 设置预设位
  setPreset: (cameraId, presetId) => api.post(`/cameras/${cameraId}/preset/${presetId}`),
  
  // 调用预设位
  gotoPreset: (cameraId, presetId) => api.post(`/cameras/${cameraId}/preset/${presetId}/goto`)
}

// 智能指令API
export const aiCommandApi = {
  // 发送文本指令
  sendTextCommand: (command) => api.post('/ai/command/text', { command }),
  
  // 发送语音指令
  sendVoiceCommand: (audioBlob) => {
    const formData = new FormData()
    formData.append('audio', audioBlob)
    return api.post('/ai/command/voice', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
  },
  
  // 获取指令历史
  getCommandHistory: () => api.get('/ai/command/history'),
  
  // 获取任务状态
  getTaskStatus: (taskId) => api.get(`/ai/task/${taskId}/status`),
  
  // 取消任务
  cancelTask: (taskId) => api.post(`/ai/task/${taskId}/cancel`)
}

// 图像分析API
export const imageAnalysisApi = {
  // 分析图像
  analyzeImage: (imageBlob, analysisType = 'general') => {
    const formData = new FormData()
    formData.append('image', imageBlob)
    formData.append('type', analysisType)
    return api.post('/ai/image/analyze', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
  },
  
  // 获取分析历史
  getAnalysisHistory: () => api.get('/ai/image/history'),
  
  // 对比图像
  compareImages: (image1, image2) => {
    const formData = new FormData()
    formData.append('image1', image1)
    formData.append('image2', image2)
    return api.post('/ai/image/compare', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
  }
}

// BIM模型API
export const bimApi = {
  // 获取BIM模型数据
  getModelData: (floorId) => api.get(`/bim/model/${floorId}`),
  
  // 获取楼层列表
  getFloors: () => api.get('/bim/floors'),
  
  // 更新机器狗在BIM中的位置
  updateRobotPosition: (x, y, z, floorId) => api.post('/bim/robot/position', { x, y, z, floorId }),
  
  // 获取路径规划
  getPathPlanning: (startPos, endPos, floorId) => api.post('/bim/path/plan', { startPos, endPos, floorId }),
  
  // 标记数据采集点
  markDataPoint: (x, y, z, floorId, data) => api.post('/bim/data/mark', { x, y, z, floorId, data }),
  
  // 获取数据采集历史
  getDataHistory: (floorId) => api.get(`/bim/data/history/${floorId}`)
}

// 系统API
export const systemApi = {
  // 获取系统状态
  getSystemStatus: () => api.get('/system/status'),
  
  // 获取系统日志
  getLogs: (level = 'info', limit = 100) => api.get('/system/logs', { params: { level, limit } }),
  
  // 系统健康检查
  healthCheck: () => api.get('/system/health'),
  
  // 获取系统配置
  getConfig: () => api.get('/system/config'),
  
  // 更新系统配置
  updateConfig: (config) => api.post('/system/config', config)
}

export default api